package CountDownLatch_5;
import java.util.concurrent.CountDownLatch;
public class 并行任务启动_并发测试准备 {
    public static void main(String[] args) throws InterruptedException {
        final int TASK_COUNT = 15;
        final CountDownLatch readySignal = new CountDownLatch(TASK_COUNT);
        final CountDownLatch startSignal = new CountDownLatch(1);
        final CountDownLatch doneSignal = new CountDownLatch(TASK_COUNT);
        // 创建测试任务
        for (int i = 0; i < TASK_COUNT; i++) {
            final int taskId = i;
            new Thread(new Runnable() {
                public void run() {
                    try {
                        // 模拟任务准备时间
                        Thread.sleep((long)(Math.random() * 500));
                        System.out.println("任务-" + taskId + " 准备就绪");
                        readySignal.countDown();

                        startSignal.await(); // 等待开始信号

                        System.out.println("任务-" + taskId + " 开始执行");
                        Thread.sleep((long)(Math.random() * 2000)); // 模拟任务执行时间

                        System.out.println("任务-" + taskId + " 执行完成");
                        doneSignal.countDown();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }

        System.out.println("主线程等待所有任务准备就绪");
        readySignal.await();

        System.out.println("所有任务已就绪，3秒后同时开始...");
        Thread.sleep(3000);
        startSignal.countDown(); // 同时启动所有任务

        System.out.println("主线程等待所有任务完成");
        doneSignal.await();

        System.out.println("所有任务已完成");
    }
}